<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" :width="formType != 'create' ? 1500 : 1200" class="bug-dialog"
    :close-on-click-modal="false" @full-screen="handleFullScreenChange">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="100px"
      class="form-inline" :disabled="formType == 'view'">
      <div class="base">
        <header>基本属性:</header>
        <el-form-item label="版本:" prop="projectVersionId">
          <el-select v-model="formData.projectVersionId" clearable filterable placeholder="请选择版本"
            :disabled="disabledPermission || updateDisPermission">
            <el-option v-for="item in versionList" :key="item.id" :label="item.versionName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="提测版本:" prop="requestFormId">
          <el-select v-model="formData.requestFormId" placeholder="请选择提测版本" filterable clearable
            :disabled="disabledPermission || updateDisPermission">
            <el-option v-for="item in commitList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="报告员:" prop="creator">
          <el-select v-model="formData.creator" filterable clearable placeholder="请选择报告员" :disabled="true"
            v-if="formType != 'create'">
            <el-option v-for="item in memberList" :key="item.memberId" :label="item.memberName"
              :value="item.memberId + ''" />
          </el-select>
          <el-input v-model="formData.creator" :disabled="true" v-else />
        </el-form-item>
        <el-form-item label="指派人:" prop="developer">
          <el-select v-model="formData.developer" clearable placeholder="请选择指派人"
            filterable>
            <el-option v-for="item in memberList" :key="item.memberName" :label="item.memberName"
              :value="item.memberId" />
          </el-select>
        </el-form-item>
        <el-form-item label="问题类型:" prop="bugType">
          <el-select v-model="formData.bugType" clearable placeholder="请选择问题类型"
            :disabled="disabledPermission || updateDisPermission">
            <el-option v-for="item in getIntDictOptions(DICT_TYPE.BUG_TYPE)" :key="item.value" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="严重级别:" prop="bugLevel">
          <el-select v-model="formData.bugLevel" clearable placeholder="请选择严重级别"
            :disabled="disabledPermission || updateDisPermission">
            <el-option v-for="item in getIntDictOptions(DICT_TYPE.BUG_LEVEL)" :key="item.value" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态:" prop="bugStatus">
          <el-select v-model="formData.bugStatus" clearable placeholder="请选择状态" @change="changeStatus">
            <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled"/>
          </el-select>
        </el-form-item>
        <el-form-item label="优先级:" prop="bugPriority">
          <el-select v-model="formData.bugPriority" clearable placeholder="请选择优先级"
            :disabled="disabledPermission || updateDisPermission">
            <el-option v-for="item in getIntDictOptions(DICT_TYPE.PRIORITY)" :key="item.value" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="出现频率:" prop="bugProbability">
          <el-select v-model="formData.bugProbability" clearable placeholder="请选择出现频率"
            :disabled="disabledPermission || updateDisPermission">
            <el-option v-for="item in getIntDictOptions(DICT_TYPE.PROBABILITY)" :key="item.value" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="对应用例:" prop="testCaseId" class="case-item">
          <el-tooltip content="可复制测试执行用例标识获取测试计划、提测版本、测试用例集和对应用例" placement="top" effect="light" class="case-tips">
            <el-icon>
              <InfoFilled />
            </el-icon>
          </el-tooltip>
          <el-select v-model="formData.testCaseId" multiple placeholder="请选择对应用例"
            :disabled="disabledPermission || updateDisPermission" filterable clearable @input="handleCaseInput">
            <el-option v-for="item in testCasesList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="测试计划:" prop="testPlanId">
          <el-select v-model="formData.testPlanId" filterable clearable placeholder="请选择测试计划"
            :disabled="disabledPermission || updateDisPermission" @change="getTestCasesList">
            <el-option v-for="item in testPlanList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="测试用例集:" prop="testPlanCasesId">
          <el-tree-select v-model="formData.testPlanCasesId" :data="testPlanCasesList" check-strictly
            :props="{ label: 'name', value: 'id' }" filterable clearable node-key="id" @change="getTestCasesList"
            placeholder="请选择测试用例集" :render-after-expand="false" :disabled="disabledPermission || updateDisPermission" />
        </el-form-item>
        <el-form-item label="影响域分析:" prop="bugInfluence" style="width: 96%" v-if="isShowReason">
          <el-input v-model="formData.bugInfluence" placeholder="请输入影响域分析" type="textarea" />
        </el-form-item>
        <el-form-item label="问题原因:" prop="bugReason" style="width: 96%" v-if="isShowReason">
          <el-input v-model="formData.bugReason" placeholder="请输入问题原因" type="textarea" />
        </el-form-item>
        <el-form-item label="解决措施:" prop="bugSolution" style="width: 96%" v-if="isShowReason">
          <el-input v-model="formData.bugSolution" placeholder="请输入解决措施" type="textarea" />
        </el-form-item>
        <el-form-item label="关闭版本:" prop="closeVersionId" v-if="isShowCloseVersion">
          <el-select v-model="formData.closeVersionId" placeholder="请选择关闭版本" filterable clearable
            :disabled="disabledPermission || updateDisPermission">
            <el-option v-for="item in commitList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="测试环境:" prop="environment">
          <el-input v-model="formData.environment" placeholder="请输入测试环境" />
        </el-form-item>
      </div>
      <div class="desc">
        <header>问题描述:</header>
        <el-form-item label="问题描述:" prop="description" style="width: 100%">
          <el-input v-model="formData.description" placeholder="请输入问题描述" type="textarea" rows="5"
            :disabled="disabledPermission || updateDisPermission" />
        </el-form-item>
        <el-form-item label="问题详情:" prop="bugDetails" style="width: 100%">
          <el-input v-model="formData.bugDetails" placeholder="请输入问题详细信息，包括问题复现步骤" type="textarea"
            :disabled="disabledPermission || updateDisPermission" rows="8" />
        </el-form-item>
        <el-form-item label="附件:" prop="file" class="upload-wrap">
          <UploadFile @success="handleUploadFiles" ref="defectUpload" :fileList="fileList" :pasteImg="imageUrl"
            v-if="formType != 'view'" />
          <div ref="dropArea" class="paste" @paste.prevent="(e) => handlePaste(e, true)" tabindex="0"
            v-if="formType != 'view'">
            <template v-if="imageUrl.length">
              <span v-for="img of imageUrl" :key="img" class="paste-img" :class="{ fullscreen: img.isFullscreen }"
                @dblclick="toggleFullscreen(img)">
                <el-image :src="img.url" title="双击放大预览" />
                <el-button @click="deleteImage(img)" circle size="small" v-if="!img.isFullscreen"
                  title="删除图片">×</el-button>
                <!-- 添加一个关闭按钮，仅在全屏预览时显示 -->
                <button v-if="img.isFullscreen" class="close-button" @click="toggleFullscreen(img)"
                  title="关闭预览">×</button>
              </span>
            </template>
            <p>点击此处粘贴图片(Ctrl+V)</p>
          </div>
          <div class="gap-2 file-wrap" v-if="formType == 'view'">
            <template v-if="fileList && fileList.length">
              <div v-for="item of viewDocFiles" :key="item.name" class="file-view">
                <el-tag type="primary">{{ item.name }} </el-tag>
                <span class="btn" @click="handleView(item.url)">预览</span><span class="btn"
                  @click="download(item)">下载</span>
              </div>
              <viewFile :file-list="viewImgFiles" />
            </template>
            <span v-else>暂无附件</span>
          </div>
        </el-form-item>
      </div>
    </el-form>
    <div class="log" v-if="formType != 'create'">
      <header>问题日志:
        <el-tooltip class="box-item" effect="dark" content="新增问题备注" placement="top-start"
          v-hasPermi="['bug:bug-log:create']" v-if="formType != 'view'">
          <el-button plain type="primary" @click="handleAddLog('create')"> 新增问题备注 </el-button>
        </el-tooltip>
      </header>
      <el-table :data="activities" :show-overflow-tooltip="true" :height="height">
        <el-table-column align="center" label="日期" prop="createTime" :formatter="dateFormatter" />
        <el-table-column align="center" label="问题活动" prop="bugOperation" />
        <el-table-column align="center" label="成员" prop="creator">
          <template #default="scope">
            <span>{{ findName(scope.row.creator) }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="scope">
            <el-button link type="primary" @click="handleAddLog('view', scope.row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm" v-if="formType != 'view'">确 定</el-button>
      <el-button @click="dialogVisible = false">{{
    formType != 'view' ? '取 消' : '关 闭'
  }}</el-button>
    </template>
  </Dialog>

  <!-- 新增日志 -->
  <el-drawer v-model="dialogLog" :title="logFormType == 'create' ? '新增问题备注' : '详情'" direction="rtl" class="demo-drawer"
    v-if="dialogLog" :size="600">
    <div class="demo-drawer__content">
      <el-form :model="form" v-loading="loading" ref="logFormRef" :rules="formLogRules" label-width="60">
        <el-form-item label="描述:" prop="bugOperation">
          <el-input v-model="form.bugOperation" placeholder="请输入问题描述" type="textarea" rows="5"
            v-if="logFormType == 'create'" />
          <span v-else>{{ form.bugOperation }}</span>
        </el-form-item>
        <el-form-item label="附件:" prop="bugEnclosure" class="bug-log_file">
          <UploadFile @success="handleUploadFilesLog" ref="logUpload" v-if="logFormType == 'create'"
            :pasteImg="imageUrlLog" />
          <div ref="dropArea" class="paste" @paste.prevent="(e) => handlePaste(e, false)" tabindex="0"
            v-if="logFormType == 'create'">
            <template v-if="imageUrlLog.length">
              <span v-for="img of imageUrlLog" :key="img" class="paste-img" :class="{ fullscreen: img.isFullscreen }"
                @dblclick="toggleFullscreen(img)">
                <el-image :src="img.url" title="双击放大预览" />
                <el-button @click="deleteImageLog(img)" circle size="small" v-if="!img.isFullscreen"
                  title="删除图片">×</el-button>
                <!-- 添加一个关闭按钮，仅在全屏预览时显示 -->
                <button v-if="img.isFullscreen" class="close-button" @click="toggleFullscreen(img)"
                  title="关闭预览">×</button>
              </span>
            </template>
            <p>点击此处粘贴图片(Ctrl+V)</p>
          </div>
          <div class="gap-2 file-wrap" v-else>
            <template v-if="fileListLog && fileListLog.length">
              <div v-for="item of viewDocLogFiles" :key="item.name" class="file-view">
                <el-tag type="primary">{{ item.name }} </el-tag>
                <el-button class="btn" @click="handleView(item.url)" size="small">预览</el-button><el-button class="btn"
                  @click="download(item)" size="small">下载</el-button>
              </div>
              <viewFile :file-list="viewImgLogFiles" />
            </template>
            <span v-else>暂无附件</span>
          </div>
        </el-form-item>
      </el-form>
      <div class="demo-drawer__footer">
        <el-button @click="cancelForm">{{ logFormType == 'create' ? '取消' : '关闭' }}</el-button>
        <el-button type="primary" :loading="loading" @click="onClick" v-if="logFormType == 'create'">
          {{ loading ? '保存中 ...' : '保存' }}
        </el-button>
      </div>
    </div>
  </el-drawer>
</template>
<script lang="ts" setup>
defineOptions({ name: 'UpdateForm' })
import * as DefectApi from '@/api/defect'
import { CirclePlus, InfoFilled } from '@element-plus/icons-vue'
import { useAppStore } from '@/store/modules/app'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import UploadFile from './component/UploadFileCom.vue'
import viewFile from './component/ViewImgFileCom.vue'
import { getTestboxTree, getTestformList, getPage } from '@/api/usecase'
import { getProjectMemberList } from '@/api/project'
import { getDemandList, getProjectMemberRole } from '@/api/demand'
import { downloadByUrl1 } from '@/utils/filt'
import { useUserStore } from '@/store/modules/user'
import { getPlanList, getCaseList, getCaseListByName } from '@/api/testPlan'
import { debounce } from 'lodash-es'
const userStore = useUserStore()
const userName = computed(() => userStore.user.nickname ?? '')
const userId = computed(() => userStore.user.id ?? '')
const appStore = useAppStore()
const projectId = computed(() => appStore.getSelectProject)
const { t } = useI18n()
const message = useMessage()
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formData = ref({} as any)
const formRules = reactive({
  projectVersionId: [{ required: true, message: '版本不能为空', trigger: 'change' }],
  developer: [{ required: true, message: '指派人不能为空', trigger: 'change' }],
  bugType: [{ required: true, message: '问题类型不能为空', trigger: 'change' }],
  bugLevel: [{ required: true, message: '问题级别不能为空', trigger: 'change' }],
  bugProbability: [{ required: true, message: '出现频率不能为空', trigger: 'change' }],
  bugPriority: [{ required: true, message: '优先级不能为空', trigger: 'change' }],
  bugStatus: [{ required: true, message: '问题状态不能为空', trigger: 'change' }],
  requestFormId: [{ required: true, message: '提测版本不能为空', trigger: 'change' }],
  description: [{ required: true, message: '描述不能为空', trigger: 'blur' }]
})
const formLogRules = reactive({
  bugOperation: [{ required: true, message: '问题描述不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const logFormRef = ref() //日志表单ref
const activities = ref([] as any) //日志列表
const dialogLog = ref(false) // 日志弹窗
const loading = ref(false)
const memberList = ref([] as any) // 用户列表
const versionList = ref([] as any) // 版本列表
const testPlanCasesList = ref([] as any) // 测试用例集
const testCasesList = ref([] as any) // 测试用例集
const fileList = ref([] as any) // 问题文件列表
const fileListLog = ref([] as any) // 日志文件列表
const form = ref({} as any) // 新增问题日志表单
const bugId = ref('') // 问题单id
const logUpload = ref() // 日志上传ref
const defectUpload = ref() // 问题单上传ref
const isShowReason = ref(false)
const isShowCloseVersion = ref(false)
const logFormType = ref()
const role = ref('')
const imageUrl = ref([] as any)
const imageUrlLog = ref([] as any)
const dropArea = ref()
const height = ref('500px') // 表格高度
const commitList = ref([] as any)
const testPlanList = ref([] as any) // 测试计划
const viewImgFiles = ref([] as any)
const viewDocFiles = ref([] as any)
const viewImgLogFiles = ref([] as any)
const viewDocLogFiles = ref([] as any)
const disabledPermission = computed(() => {
  return ['projectManager', 'developer'].includes(role.value) && formType.value == 'update'
})
const updateDisPermission = computed(() => {
  return formType.value == 'update' && formData.value.creator != userId.value
})
const statusList = computed(() => {
  const list = getIntDictOptions(DICT_TYPE.BUG_STATUS)
  if (['projectManager', 'developer'].includes(role.value)) {
    list.forEach(l=>{
      if(l.label.indexOf('已关闭') != -1){
        l.disabled = true
      }
    })
  }
  return list
})
const findDevelopId = (name)=>{
  return memberList.value.find(m=>m.memberName == name)?.memberId
}
/** 打开弹窗 */
const open = async (type: string, row: any) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  isShowReason.value = false
  isShowCloseVersion.value = false
  getProjectMemberRoleFn()
  resetForm()
  await getMembers()
  getVersion()
  getTestPlan()
  getTestPlanCasesList()
  getCommitList()
  // 修改时，设置数据
  if (row) {
    fileList.value = JSON.parse(row.bugEnclosure)
    filterImageAndNonImageFiles(fileList.value, 'info')
    isShowReason.value = row.bugStatus == 2
    isShowCloseVersion.value = row.bugStatus == 7
    bugId.value = row.id
    formLoading.value = true
    try {
      formData.value = {
        ...row,
        developer:findDevelopId(row.developer),
        projectId: projectId.value
      }
      getLogs(row.id)
      getTestCasesList()
    } finally {
      formLoading.value = false
    }
  }
}
watch(
  () => isShowReason.value,
  (newVal) => {
    if (!newVal) {
      formData.value = {
        ...formData.value,
        bugInfluence: '',
        bugReason: '',
        bugSolution: ''
      }
    }
  }
)

watch(
  () => isShowCloseVersion.value,
  (newVal) => {
    if (!newVal) {
      formData.value = {
        ...formData.value,
        closeVersionId: ''
      }
    }
  }
)

function filterImageAndNonImageFiles(filesArray, type) {
  viewImgFiles.value = []
  viewImgLogFiles.value = []
  viewDocFiles.value = []
  viewDocLogFiles.value = []
  filesArray.length && filesArray.forEach((file) => {
    // 判断文件是否为图片，可以通过检查MIME类型或文件扩展名
    if (isImageFile(file)) {
      type == 'info' ? viewImgFiles.value.push(file) : viewImgLogFiles.value.push(file)
    } else {
      type == 'info' ? viewDocFiles.value.push(file) : viewDocLogFiles.value.push(file)
    }
  })
}
// 判断文件是否为图片的辅助函数
function isImageFile(file) {
  const fileName = file.name
  const fileExtension = fileName.split('.').pop().toLowerCase()
  const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']
  return imageExtensions.includes(fileExtension)
}
// 对应用例输入
const handleCaseInput = debounce(async (event) => {
  const inputValue = event.target.value
  const data = await DefectApi.getTestCaseByLogo({ logo: inputValue })
  if (data) {
    formData.value = {
      ...formData.value,
      requestFormId: data.requestFormId,
      testPlanCasesId: data.testSuiteId,
      testPlanId: data.testPlanId
    }
    await getTestCasesList() // 获取该输入框下拉数据
    formData.value.testCaseId = [data.id]
  } else {
    message.warning('未查询到该用例相关信息')
  }
}, 1000)

// 弹窗全屏
const handleFullScreenChange = (val) => {
  const windowHeight = document.documentElement.offsetHeight
  if (val) {
    height.value = `${windowHeight - 200}px`
  } else {
    height.value = `${windowHeight - 300}px`
  }
}

// 复制粘贴
const handlePaste = async (e, flag) => {
  const items = e.clipboardData.items
  for (let i = 0; i < items.length; i++) {
    const item = items[i]
    if (item.type.indexOf('image') === 0) {
      const file = item.getAsFile()
      if (file) {
        // 将File对象转换为Base64
        const base64Image = await convertFileToBase64(file)
        if (flag) {
          imageUrl.value.push({ url: base64Image, file: file, isFullscreen: false })
        } else {
          imageUrlLog.value.push({ url: base64Image, file: file, isFullscreen: false })
        }
      }
    }
  }
  if ((fileList.value.length + imageUrl.value.length > 5)) {
    message.error('上传文件数量不能超过5个！')
    imageUrl.value.pop()
    return
  }
  if ((fileListLog.value.length + imageUrlLog.value.length > 5)) {
    message.error('上传文件数量不能超过5个！')
    imageUrlLog.value.pop()
    return
  }
}

// 将File对象转换为Base64编码的辅助函数
const convertFileToBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = (event) => {
      resolve(event.target?.result)
    }
    reader.onerror = (error) => {
      reject(error)
    }
    reader.readAsDataURL(file)
  })
}
// 删除图片的方法
const deleteImage = (img) => {
  imageUrl.value = imageUrl.value.filter((i) => i.url != img.url)
}
const deleteImageLog = (img) => {
  imageUrlLog.value = imageUrlLog.value.filter((i) => i.url != img.url)
}
// 双击图片时切换全屏预览状态
const toggleFullscreen = (img) => {
  img.isFullscreen = !img.isFullscreen
}
// 查找name
const findName = (id) => {
  const result = memberList.value.find((k) => k.memberId == id)
  if (result) {
    return result.memberName
  }
  return '-'
}
// 状态切换
const changeStatus = (val) => {
  isShowReason.value = val == 2
  isShowCloseVersion.value = val == 7
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: '',
    description: '',
    bugType: 1,
    bugLevel: 2,
    bugStatus: 1,
    bugPriority: 3,
    bugProbability: 7,
    projectVersionId: '',
    testPlanId: '',
    testPlanCasesId: '',
    testCaseId: [],
    developer: '',
    creator: userName.value,
    bugDetails: '',
    bugEnclosure: '',
    bugInfluence: '',
    bugReason: '',
    bugSolution: '',
    closeVersionId: '',
    requestFormId: '',
    environment: 'Windows 10',
    projectId: projectId.value
  }
  fileList.value = []
  imageUrl.value = []
  formRef.value?.resetFields()
}
// 重置日志表单
const resetFormLog = () => {
  form.value = {
    bugId: bugId.value,
    bugOperation: '',
    bugEnclosure: ''
  }
  fileListLog.value = []
  imageUrlLog.value = []
  logFormRef.value?.resetFields()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

// 获取测试计划
const getTestPlan = async () => {
  let data = await getPlanList({ projectId: projectId.value })
  testPlanList.value = data
}
// 获取提测单
const getCommitList = async () => {
  commitList.value = []
  let data = await getTestformList({
    projectId: projectId.value
  })
  commitList.value = data.map((item) => {
    return {
      label: `${item.version.versionName}版本-${item.rounds}轮次`,
      value: item.id
    }
  })
}

// 获取测试用例集
const getTestPlanCasesList = async () => {
  let data = await getTestboxTree({ projectId: projectId.value })
  testPlanCasesList.value = data ? [data] : []
}

// 获取对应用例
const getTestCasesList = async () => {
  const params = {
    projectId: projectId.value,
    testSuiteId: formData.value.testPlanCasesId,
    testPlanId: formData.value.testPlanId
  }
  let data = await getCaseListByName(params)
  testCasesList.value = data
}

// 获取成员列表
const getMembers = async () => {
  let data = await getProjectMemberList({
    pageNo: 1,
    pageSize: 100,
    projectId: projectId.value
  })
  memberList.value = data
}

// 获取版本列表
const getVersion = async () => {
  let data = await getDemandList({
    pageNo: 1,
    pageSize: 100,
    projectId: projectId.value
  })
  versionList.value = data.list
}

// 创建问题文件操作完成
const handleUploadFiles = (files) => {
  fileList.value = files
}
// 创建问题日志文件操作完成
const handleUploadFilesLog = (files) => {
  fileListLog.value = files
}
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = {
      id: formData.value.id || '',
      description: formData.value.description || '',
      bugType: formData.value.bugType || '',
      bugLevel: formData.value.bugLevel || '',
      bugStatus: formData.value.bugStatus || '',
      bugPriority: formData.value.bugPriority || '',
      bugProbability: formData.value.bugProbability || '',
      projectVersionId: formData.value.projectVersionId || '',
      testPlanId: formData.value.testPlanId || '',
      testPlanCasesId: formData.value.testPlanCasesId || '',
      testCaseId: formData.value.testCaseId || [],
      developer: formData.value.developer || '',
      creator: userName.value,
      bugDetails: formData.value.bugDetails || '',
      bugEnclosure: formData.value.bugEnclosure || '',
      bugInfluence: formData.value.bugInfluence || '',
      bugReason: formData.value.bugReason || '',
      bugSolution: formData.value.bugSolution || '',
      projectId: projectId.value,
      requestFormId: formData.value.requestFormId || '',
      closeVersionId: formData.value.closeVersionId || '',
      environment: formData.value.environment || ''
    }
    const formDataObj = new FormData()
    if (fileList.value.length) {
      fileList.value.forEach((item) => {
        if (item.raw) {
          formDataObj.append(`files`, item.raw, item.name)
        } else {
          formDataObj.append(`files`, new Blob([item.url], { type: '' }), item.name)
        }
      })
    }
    if (imageUrl.value.length) {
      imageUrl.value.forEach((item, index) => {
        if (item.file) {
          formDataObj.append(`files`, item.file, '粘贴图片' + new Date().getTime() + index + '.png')
        }
      })
    }
    if (!fileList.value.length && !imageUrl.value.length) {
      formDataObj.append('files', new Blob([], { type: '' }))
    }
    console.log('缺陷管理表单数据', data, printFormData(formDataObj))
    if (formType.value === 'create') {
      formDataObj.append(
        'createReqVO',
        new Blob([JSON.stringify(data)], { type: 'application/json' })
      )
      await DefectApi.createDefect(formDataObj)
      message.success(t('common.createSuccess'))
    } else {
      formDataObj.append(
        'updateReqVO',
        new Blob([JSON.stringify(data)], { type: 'application/json' })
      )
      await DefectApi.updateDefect(formDataObj)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
const printFormData = (formData) => {
  const formDataEntries = [...formData.entries()]
  const formDataObject = formDataEntries.reduce((obj, [key, value]) => {
    obj[key] = value
    return obj
  }, {})

  return formDataObject
}
// 新增日志
const handleAddLog = (type, data?) => {
  dialogLog.value = true
  logFormType.value = type
  resetFormLog()
  if (data) {
    form.value = data
    fileListLog.value = JSON.parse(data.bugEnclosure)
    filterImageAndNonImageFiles(fileListLog.value, 'log')
  }
}
// 日志列表
const getLogs = async (id) => {
  let data = await DefectApi.getDefectLogList({ id })
  activities.value = data
}
// 保存日志
const onClick = async () => {
  // 校验表单
  if (!logFormRef) return
  const valid = await logFormRef.value.validate()
  if (!valid) return
  loading.value = true
  try {
    const data = form.value
    const formDataObj = new FormData()
    formDataObj.append(
      'createReqVO',
      new Blob([JSON.stringify(data)], { type: 'application/json' })
    )
    if (fileListLog.value.length) {
      fileListLog.value.forEach((item) => {
        if (item.raw) {
          formDataObj.append(`files`, item.raw, item.name)
        }
      })
    }
    if (imageUrlLog.value.length) {
      imageUrlLog.value.forEach((item, index) => {
        if (item.file) {
          formDataObj.append(`files`, item.file, '粘贴图片' + new Date().getTime() + index + '.png')
        }
      })
    }
    if (!fileListLog.value.length && !imageUrlLog.value.length) {
      formDataObj.append('files', new Blob([], { type: '' }))
    }
    await DefectApi.createDefectLog(formDataObj)
    message.success(t('common.createSuccess'))
    getLogs(bugId.value)
  } finally {
    loading.value = false
    dialogLog.value = false
  }
}
// 日志取消
const cancelForm = () => {
  loading.value = false
  dialogLog.value = false
}
// 下载
const download = (val) => {
  if (!val || !val.url) {
    message.warning('无连接')
    return
  }
  // 创建隐藏的可下载链接
  const element = document.createElement('a')
  element.setAttribute('href', val.url)
  element.setAttribute('download', val.name)

  // 触发点击
  document.body.appendChild(element)
  element.click()

  // 然后移除
  document.body.removeChild(element)
  // downloadByUrl1({ url: val.url, fileName: val.name })
}
// 预览
const handleView = (url) => {
  if (!url) {
    message.warning('无链接')
    return
  }
  window.open(`${url}`, '_blank')
}
// 获取人员在项目中角色
const getProjectMemberRoleFn = async () => {
  let data = await getProjectMemberRole({ projectId: projectId.value })
  role.value = data
}
</script>

<style lang="scss">
.bug-log_file {
  .el-form-item__content {
    display: flex;
    align-items: flex-start;
  }
}

.paste {
  padding: 10px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  box-sizing: border-box;
  text-align: center;
  cursor: pointer;
  position: relative;
  overflow: auto;
  margin-left: 10px;
  min-height: 145px;
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;

  &-img {
    position: relative;
    margin-right: 15px;
    display: inline-block;
    width: 100px;
    height: 100px;
    margin-bottom: 5px;

    .el-image {
      width: 100%;
      height: 100%;
    }

    .el-button {
      position: absolute;
      right: -10px;
      top: -10px;
      display: none;
      background-color: rgba(0, 0, 0, 0.5);
      color: white;
      border: none;
      padding: 5px 10px;
      cursor: pointer;
      font-weight: bold;
      border-radius: 50%;
    }

    &:hover {
      .el-button {
        display: flex;
      }
    }
  }
}

.fullscreen {
  position: fixed !important;
  left: 5% !important;
  top: 5% !important;
  width: 90% !important;
  height: 90% !important;
  object-fit: contain !important;
  z-index: 9999 !important;
}

.close-button {
  position: absolute;
  top: -10px;
  right: -10px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  padding: 5px 10px;
  cursor: pointer;
  font-weight: bold;
  border-radius: 50%;
}

.bug-dialog {
  .case-item {
    .el-form-item__label {
      padding: 0 22px 0 0;
    }

    .el-icon.el-tooltip__trigger {
      position: absolute;
      left: -18px;
    }
  }

  .upload-wrap {
    .el-form-item__content {
      display: flex;
      justify-content: left;
      align-items: flex-start;
    }
  }


  .el-form {
    display: flex;
    justify-content: space-between;
    width: 100%;
  }

  .el-dialog__body {
    display: flex;
    justify-content: space-between;
  }

  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  header {
    font-weight: bold;
    margin-bottom: 10px;
    margin-left: 13px;
  }

  .base {
    padding: 10px 0 0;
    margin-bottom: 10px;
  }

  .desc {
    padding: 10px 30px 0 0;
    margin-bottom: 10px;
    margin-left: 20px;
    flex: 1;
  }

  .log {
    flex: 1;
    min-width: 500px;

    header {
      display: flex;
      justify-content: space-between;
    }
  }

  :deep(.el-collapse-item__header) {
    font-weight: bold;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }

  .form-inline .el-input {
    --el-input-width: 180px;
  }

  .form-inline .el-select {
    --el-select-width: 180px;
  }
}

.file-view {
  .btn {
    margin: 0 5px;
    display: inline-block;
    cursor: pointer;
    height: 24px;
    line-height: 13px;
    padding: 5px 11px;
    font-size: 12px;
    border-radius: 4px;
    box-sizing: border-box;
    border: 1px solid #dcdfe6;

    &:hover {
      color: #409eff;
      border-color: #c6e2ff;
      background-color: #ecf5ff;
      outline: 0;
    }
  }
}
</style>
